// 密码输入对话框组件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/cashier/provider/common_http_provider.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:get/get.dart';

class PasswordInputDialog extends StatefulWidget {
  const PasswordInputDialog({super.key, required this.onPasswordValidated});

  final void Function(String) onPasswordValidated;

  @override
  State<PasswordInputDialog> createState() => _PasswordInputDialogState();
}

class _PasswordInputDialogState extends State<PasswordInputDialog> {
  String _password = '';
  bool _isVerifying = false;
  String _errorMessage = '';
  final FocusNode _focusNode = FocusNode();
  final commonHttpProvider = Get.find<CommonHttpProvider>();

  @override
  void initState() {
    super.initState();
    // 请求焦点以接收键盘事件
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colours.bg,
      title: const Text('请输入支付密码'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 密码显示区域
          _buildPasswordDisplay(),
          const SizedBox(height: 20),
          // 错误信息
          if (_errorMessage.isNotEmpty)
            Text(
              _errorMessage,
              style: const TextStyle(color: Colors.red, fontSize: 14),
            ),
          const SizedBox(height: 10),
          // 数字键盘
          _buildNumberPad(),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text('取消'),
        ),
      ],
    );
  }

  // 构建密码显示区域
  Widget _buildPasswordDisplay() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(6, (index) {
        return Container(
          width: 40,
          height: 40,
          margin: const EdgeInsets.symmetric(horizontal: 5),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Text(
              index < _password.length ? '•' : '',
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
          ),
        );
      }),
    );
  }

  // 构建数字键盘 (微信支付风格)
  Widget _buildNumberPad() {
    return Container(
      margin: const EdgeInsets.only(top: 10),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        spacing: 10,
        children: [
          // 添加键盘监听器
          RawKeyboardListener(
            focusNode: _focusNode,
            onKey: _handleKeyEvent,
            child: Container(),
          ),
          // 第一行 1, 2, 3
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildWeChatStyleNumberButton(1),
              _buildWeChatStyleNumberButton(2),
              _buildWeChatStyleNumberButton(3),
            ],
          ),
          // 第二行 4, 5, 6
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildWeChatStyleNumberButton(4),
              _buildWeChatStyleNumberButton(5),
              _buildWeChatStyleNumberButton(6),
            ],
          ),
          // 第三行 7, 8, 9
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildWeChatStyleNumberButton(7),
              _buildWeChatStyleNumberButton(8),
              _buildWeChatStyleNumberButton(9),
            ],
          ),
          // 第四行 空, 0, 删除
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              const SizedBox(width: 100), // 空位占位
              _buildWeChatStyleNumberButton(0),
              const SizedBox(width: 5), // 空位占位
              _buildWeChatStyleDeleteButton(), // 删除按钮
            ],
          ),
        ],
      ),
    );
  }

  // 处理键盘事件
  void _handleKeyEvent(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      // 优化键盘事件处理逻辑
      final key = event.logicalKey;

      // 处理数字键
      if (key == LogicalKeyboardKey.digit0 || key == LogicalKeyboardKey.numpad0) {
        _addDigit('0');
      } else if (key == LogicalKeyboardKey.digit1 || key == LogicalKeyboardKey.numpad1) {
        _addDigit('1');
      } else if (key == LogicalKeyboardKey.digit2 || key == LogicalKeyboardKey.numpad2) {
        _addDigit('2');
      } else if (key == LogicalKeyboardKey.digit3 || key == LogicalKeyboardKey.numpad3) {
        _addDigit('3');
      } else if (key == LogicalKeyboardKey.digit4 || key == LogicalKeyboardKey.numpad4) {
        _addDigit('4');
      } else if (key == LogicalKeyboardKey.digit5 || key == LogicalKeyboardKey.numpad5) {
        _addDigit('5');
      } else if (key == LogicalKeyboardKey.digit6 || key == LogicalKeyboardKey.numpad6) {
        _addDigit('6');
      } else if (key == LogicalKeyboardKey.digit7 || key == LogicalKeyboardKey.numpad7) {
        _addDigit('7');
      } else if (key == LogicalKeyboardKey.digit8 || key == LogicalKeyboardKey.numpad8) {
        _addDigit('8');
      } else if (key == LogicalKeyboardKey.digit9 || key == LogicalKeyboardKey.numpad9) {
        _addDigit('9');
      }
      // 处理退格键
      else if (key == LogicalKeyboardKey.backspace) {
        _deleteDigit();
      }
    }
  }

  // 添加数字到密码
  void _addDigit(String digit) {
    // 优化条件判断
    if (_isVerifying || _password.length >= 6) return;

    setState(() {
      _password += digit;
      _errorMessage = ''; // 清除错误信息
    });

    // 如果密码已满6位，开始验证
    if (_password.length == 6) {
      _verifyPassword();
    }
  }

  // 删除密码最后一位
  void _deleteDigit() {
    // 优化条件判断
    if (_isVerifying || _password.isEmpty) return;

    setState(() {
      _password = _password.substring(0, _password.length - 1);
      _errorMessage = ''; // 清除错误信息
    });
  }

  // 构建微信风格的数字按钮 (白色背景+圆角)
  Widget _buildWeChatStyleNumberButton(int number) {
    // return SizedBox(
    //   width: 70,
    //   height: 50,
    //   child: TextButton(
    //     onPressed: _isVerifying
    //         ? null
    //         : () {
    //             _addDigit(number.toString());
    //           },
    //     style: TextButton.styleFrom(
    //       backgroundColor: Colors.white, // 白色背景
    //       shape: RoundedRectangleBorder(
    //         borderRadius: BorderRadius.circular(3), // 圆角
    //         side: BorderSide(color: Colors.grey.shade300), // 边框
    //       ),
    //       // 禁用状态下的样式
    //       disabledForegroundColor: Colors.grey,
    //     ),
    //     child: Text(
    //       number.toString(),
    //       style: const TextStyle(
    //         fontSize: 24,
    //         fontWeight: FontWeight.w400,
    //         color: Colors.black87,
    //       ),
    //     ),
    //   ),
    // );

    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(6),
            ),
            padding: const EdgeInsets.symmetric(vertical: 16),
            side: BorderSide(color: Colors.grey.shade300),
          ),
          onPressed: _isVerifying
              ? null
              : () {
            _addDigit(number.toString());
          },
          child: Text(
            number.toString(),
            style: const TextStyle(
              fontSize: 22,
              color: Colors.black87,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

   // 构建微信风格的删除按钮 (白色背景+圆角)
  Widget _buildWeChatStyleDeleteButton() {
    return SizedBox(
      width: 95,
      height: 60,
      child: IconButton(
        onPressed: _isVerifying || _password.isEmpty
            ? null
            : () {
                _deleteDigit();
              },
        style: IconButton.styleFrom(
          // backgroundColor: Colors.white, // 设置背景色为白色
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8), // 圆角
            side: BorderSide(color: Colors.grey.shade300), // 边框
          ),
          padding: EdgeInsets.zero, // 移除默认内边距
          // 禁用状态下的样式
          disabledForegroundColor: Colors.grey,
          disabledBackgroundColor: Colors.white,
        ),
        icon: Icon(
          Icons.keyboard_backspace,
          color: Colors.black54,
          size: 28,
        ),
      ),
    );
  }


  // 验证密码
  Future<void> _verifyPassword() async {
    setState(() {
      _isVerifying = true;
      _errorMessage = ''; // 清除之前的错误信息
    });

    try {
      // 这里应该调用实际的密码验证接口
      commonHttpProvider.checkOperationPassword(
        password: _password.toMd5,
        success: (data) {
          if (mounted) {
            // 验证成功，关闭对话框并回调
            Navigator.of(context).pop();
            widget.onPasswordValidated(_password);
          }
        },
        onError: (code, msg) {
          if (mounted) {
            setState(() {
              _password = '';
              _errorMessage = '校验操作密码失败 code: $code, msg: $msg';
              _isVerifying = false;

              // 重新请求焦点
              WidgetsBinding.instance.addPostFrameCallback((_) {
                _focusNode.requestFocus();
              });
            });
          }
        },
      );
    } catch (e) {
      // 添加异常处理
      if (mounted) {
        setState(() {
          _password = '';
          _errorMessage = '网络请求异常，请稍后重试';
          _isVerifying = false;
        });
      }
    }
  }
}
